/**
 * 
 */
package cn.kuaipai.weibo.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.kuaipai.utils.BeanUtils;
import cn.kuaipai.weibo.constants.WeiboConstants;
import cn.kuaipai.weibo.model.WeiboParameter;

/**
 * 微博HTTP请求客户端
 * @author zy
 */
public class WeiboHttpClient {
	protected final Logger logger = Logger.getLogger(this.getClass());
	
	/**
	 * httpGet请求
	 * @param url
	 * @param queryString
	 * @return String
	 */
	public String httpGet(String url, String queryString){
		StringBuffer response = new StringBuffer();
		if(StringUtils.isNotBlank(queryString)){
			url += "?" + queryString  ;
		}
		logger.info("[weibo] httpGet-1 " + url);
		HttpClient httpClient = new HttpClient();
		GetMethod httpGet = new GetMethod(url);
		try {
			httpGet.getParams().setParameter("http.socket.timeout",WeiboConstants.CONNECTION_TIMEOUT);
			int statusCode = httpClient.executeMethod(httpGet);
			if (statusCode != HttpStatus.SC_OK)
				logger.error("[weibo] httpGet " + url + " [fail] statusCode!=200 " + BeanUtils.reflectionToString(httpGet.getStatusLine()));
			
			/*InputStream is = httpGet.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line ;
			while((line = br.readLine()) != null){
				response.append(line).append(System.getProperty("line.separator"));
			}
			br.close();
			is.close();*/
			
			response.append(httpGet.getResponseBodyAsString());
			
			logger.info("[weibo] httpGet-2 " + url + " response:" + response);
		} catch (Exception e) {
			logger.error("[weibo] httpGet " + url + " error!",e);
		} finally {
			httpGet.releaseConnection();
		}
		return response.toString();
	}
	
	/**
	 * HttpPost 请求
	 * 
	 * @param url
	 * @param queryString
	 * @return
	 */
	public String httpPost(String url, String queryString){
		logger.info("[weibo] httpPost-1 " + url + " " + queryString );
		StringBuffer response = new StringBuffer();
		HttpClient httpClient = new HttpClient();
		PostMethod httpPost = new PostMethod(url);
		try {
			httpPost.addParameter("Content-Type","application/x-www-form-urlencoded");
			httpPost.getParams().setParameter("http.socket.timeout",new Integer(WeiboConstants.CONNECTION_TIMEOUT));
			if (StringUtils.isNotBlank(queryString))
				httpPost.setRequestEntity(new ByteArrayRequestEntity(queryString.getBytes()));
			int statusCode = httpClient.executeMethod(httpPost);
			if (statusCode != HttpStatus.SC_OK)
				logger.error("[weibo] httpGet " + url + " [fail] statusCode!=200 " + BeanUtils.reflectionToString(httpPost.getStatusLine()));

			/*InputStream is = httpPost.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line ;
			while((line = br.readLine()) != null){
				response.append(line).append(System.getProperty("line.separator"));
			}
			br.close();
			is.close();*/
			response.append(httpPost.getResponseBodyAsString());
			logger.info("[weibo] httpPost-2 " + url + " response:" + response);
			
		} catch (Exception e) {
			logger.error("[weibo] httpPost " + url + " error!",e);
		} finally {
			httpPost.releaseConnection();
			httpClient = null;
		}
		return response.toString();
	}
	
	/**
	 * httpPost 发送附件
	 * 
	 * @param url
	 * @param queryString
	 * @param files
	 * 
	 * @return
	 */
	public String httpPostWithFile(String url, String queryString,List<WeiboParameter> files){
		StringBuffer response = new StringBuffer();
		url += '?' + queryString;
		logger.info("[weibo] httpPostWithFile-1 " + url);
		
		HttpClient httpClient = new HttpClient();
		PostMethod httpPost = new PostMethod(url);
		try {
			List<WeiboParameter> listParams = HttpUtils.getQueryParameters(queryString);
			int length = listParams.size() + (files == null ? 0 : files.size());
			Part[] parts = new Part[length];
			int i = 0;
			for (WeiboParameter param : listParams) {
				parts[i++] = new StringPart(param.getName(),
						HttpUtils.formParamDecode(param.getValue()), "UTF-8");
			}

			for (WeiboParameter param : files) {
				String filePath = param.getValue();
				File file = new File(filePath);
				String name = param.getName();
//				String fileName = file.getName();
//				String type = QHttpUtil.getContentType(file);
				// image/jpeg - image/png
				parts[i++] = new FilePart(name, file, "image/jpeg", "utf-8");
			}
		
			httpPost.setRequestEntity(new MultipartRequestEntity(parts,
					httpPost.getParams()));

			int statusCode = httpClient.executeMethod(httpPost);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("HttpPost Method failed: "
						+ httpPost.getStatusLine());
				logger.error("[weibo] httpPostWithFile " + url + " [fail] statusCode!=200 " + BeanUtils.reflectionToString(httpPost.getStatusLine()));
			}
			
			/*InputStream is = httpPost.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line ;
			while((line = br.readLine()) != null){
				response.append(line).append(System.getProperty("line.separator"));
			}
			br.close();
			is.close();*/
			response.append(httpPost.getResponseBodyAsString());
			logger.info("[weibo] httpPost-2 " + url + " response:" + response);
			
		} catch (Exception e) {
			logger.error("[weibo] httpPost " + url + " error!",e);
		} finally {
			httpPost.releaseConnection();
			httpClient = null;
		}
		return response.toString();
	}
	
}
